package com.gamerole.app.page.source

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.gamerole.app.entity.ArticleBean
import com.gamerole.app.entity.UpSearchBean
import com.gamerole.app.service.HttpService

private const val STARTING_PAGE_INDEX = 1
private const val NETWORK_PAGE_SIZE = 10

class UpSearchPagingSource constructor(
    private var httpService: HttpService,
    private var keyword: String
) :
    PagingSource<Int, UpSearchBean>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, UpSearchBean> {
        val pageNumber = params.key ?: STARTING_PAGE_INDEX
        val pageSize = params.loadSize

        // 加载数据
        val data = httpService.searchUpPan(page = pageNumber, keyword = keyword)

        return try {

            data.result.let { upSearchBeanPageBean ->
                if (upSearchBeanPageBean != null) {
                    upSearchBeanPageBean.list = upSearchBeanPageBean.list?.filter { it.id != "-1" }
                }
                val nextKey = if (upSearchBeanPageBean!!.list!!.isEmpty()) {
                    null
                } else {
                    // initial load size = 3 * NETWORK_PAGE_SIZE
                    // ensure we're not requesting duplicating items, at the 2nd request
                    // 初次加载 params.loadSize 为 NETWORK_PAGE_SIZE 3倍数量
                    // position = 1 params.loadSize = 90 NETWORK_PAGE_SIZE = 30
                    // 后续 paging 加载 params.loadSize 为 NETWORK_PAGE_SIZE 数量
                    // position = 5 params.loadSize = 30 NETWORK_PAGE_SIZE = 30
                    // position = 4 params.loadSize = 30 NETWORK_PAGE_SIZE = 30
                    pageNumber + (params.loadSize / NETWORK_PAGE_SIZE)
                }
                LoadResult.Page(
                    data = upSearchBeanPageBean.list!!,
                    prevKey = if (pageNumber == STARTING_PAGE_INDEX) null else pageNumber - 1,
                    nextKey = nextKey
                )
            }
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    fun setType(keyword: String): UpSearchPagingSource {
        this.keyword = keyword
        return this
    }

    override fun getRefreshKey(state: PagingState<Int, UpSearchBean>): Int? {
        return null
    }
}